import logging
import time

from base.request import BaseHandler
from conf.config import MP_APP_ID
from helper.payment.wechat_base import Wechat_Base
from helper.payment.wechat_pay import WechatPay

logger = logging.getLogger("wechat.handlers")


class SubscribeHandler(BaseHandler):
    def data_received(self, chunk):
        pass

    async def get(self):

        open_id = await self.get_open_id()
        await self.bind_user(open_id)

        is_wechat = self.is_in_wechat()
        context = dict(
            title="加入莱支好酒会员",
            open_id=open_id,
            is_wechat=is_wechat,
        )

        if is_wechat:
            app_id = MP_APP_ID
            time_stamp = int(str(time.time()).split(".")[0])
            nonce_str = WechatPay.generate_nonce_str()

            host = self.request.host
            url_params = self.request.query
            request_path = self.request.path
            protocol = self.request.protocol
            full_url = protocol + "://" + host + request_path
            if url_params:
                full_url += "?" + url_params

            jsapi_ticket = self.get_jsapi_ticket()
            signature = Wechat_Base.signature(nonce_str, time_stamp, full_url, jsapi_ticket)
            logging.debug("signature：%s" % signature)
            context["app_id"] = app_id
            context["time_stamp"] = time_stamp
            context["nonce_str"] = nonce_str
            context["signature"] = signature
        return self.render_html("content/subscribe.html", **context)
